import random
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
from django.views.decorators.http import require_http_methods
from exercise.models import ExerciseInfo
from docx import Document
from django.core.paginator import Paginator
from nurse.models import NurseInfo


# Create exercise views here.


class UploadExercise(View):
    """批量导入"""

    def get(self, request):
        return render(request, 'exercise/upload-exercise.html')

    def post(self, request):
        """处理word文档"""
        try:
            parse_questions = []
            question = []
            new_question = False
            # 获得文件对象
            file = request.FILES.get('file')
            print(file)
            # 将文件对象传入Document()实例化document
            doc = Document(file)
            for para in doc.paragraphs:
                text = para.text

                if text:
                    print(text[0])
                    if text[0].isdigit():
                        new_question = True   # 当检测到的数字题号的时候，说明检测到题目的第一行了
                        question = []         # 创建一个列表开始存储一道题

                    if new_question:           # 如果当前标志位不变说明还属于同一题
                        question.append(text.strip())  # 将字符串加入题目列表中
                    
                    if text[:2] == '正确':
                        new_question = False
                        parse_questions.append(question)

            print(parse_questions)

            # 创建题目对象，将题目写入数据库
            for q in parse_questions:
                try:
                    print(q[0][3:], q[1][3:], q[2][3:], q[3][3:], q[4][3:], q[5][3:], q[6][5:], sep='\n')
                    # ExerciseInfo.objects.create(
                    #     question=q[0][3:],
                    #     option_a=q[1][3:],
                    #     option_b=q[2][3:],
                    #     option_c=q[3][3:],
                    #     option_d=q[4][3:],
                    #     option_e=q[5][3:],
                    #     answer=q[6][5:]
                    # )
                except:
                    pass
            return JsonResponse({'code': 1})

        except Exception as e:
            print(e)
            return JsonResponse({'code': 0})


class AddExercise(View):
    """逐个添加题目"""

    def get(self, request):
        return render(request, 'exercise/add-exercise.html')

    def post(self, request):

        try:
            # 题干
            question = request.POST.get('question')
            # 选项
            option_a = request.POST.get('option_a')
            option_b = request.POST.get('option_b')
            option_c = request.POST.get('option_c')
            option_d = request.POST.get('option_d')
            option_e = request.POST.get('option_e')
            option_f = request.POST.get('option_f')
            # 分类
            category = request.POST.get('category')
            # 题目上传人
            user_id = request.session.get('user_id')
            current_nurse = NurseInfo.objects.get(id=user_id)

            answer = request.POST.getlist('answer')
            description = request.POST.get('description')

            ExerciseInfo.objects.create(
                question=question,
                option_a=option_a,
                option_b=option_b,
                option_c=option_c,
                option_d=option_d,
                option_e=option_e,
                answer=answer,
                description=description,
                category=category,
                uploader=current_nurse
            )
            if (not option_f or not option_e) and (answer in ['E', 'F']):
                return JsonResponse({'code': 0})
            else:
                return JsonResponse({'code': 1})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 0})


class ShowExercise(View):
    """展示题库"""

    def get(self, request):
        # 判断当前用户的身份
        user_id = request.session.get('user_id')
        nurse = NurseInfo.objects.get(id=user_id)
        # 不同身份的人所见到的题目是不同的
        if nurse.authority == 1:  # 判断是否是超级管理员
            exercise_list = ExerciseInfo.objects.all()  # 管理员获得所有题目的列表
        else:
            # 非管理员获得自己的题目
            exercise_list = ExerciseInfo.objects.filter(uploader=nurse)
        # 将正确率与题目关联
        exercise_multi_list = []  # [{},{}...]
        # 计算每个题的正确率
        for exercise in exercise_list:
            exer_d = {}
            if exercise.total_count:
                correct_rate = exercise.correct_count / exercise.total_count * 100
                exer_d['exercise'] = exercise
                exer_d['correct_rate'] = correct_rate
                exercise_multi_list.append(exer_d)
            else:
                exer_d['exercise'] = exercise
                exer_d['correct_rate'] = 0
                exercise_multi_list.append(exer_d)

        # 分页显示
        paginator = Paginator(exercise_multi_list, 5)
        page_number = request.GET.get('page')       # 获取当前页面序号
        page_obj = paginator.get_page(page_number)  # 获取页面对象

        context = {
            'exercise_list': exercise_list,
            # 'exercise_multi_list': exercise_multi_list,
            'page_obj': page_obj
        }
        return render(request, 'exercise/show-exercise.html', context=context)


@require_http_methods('GET')
def delete_exercise(request):
    """删除题目"""
    pk = request.GET.get('id')
    ExerciseInfo.objects.filter(id=pk).delete()

    return redirect('exercise:show_exercise')


class DoExercise(View):
    """刷题做题"""
    def get(self, request):
        """根据返回的操作类型确定做题方式"""
        # 获取当前刷题的类型
        operate = request.GET.get('operate')
        # 确认当前刷题人的身份
        user_id = request.session.get('user_id')
        nurse = NurseInfo.objects.get(id=user_id)

        # try:
        if operate == 'random':
            # 根据身份抽取他有权访问的题目
            if nurse.authority == 1:
                exercise_list = ExerciseInfo.objects.all()
            else:
                exercise_list = ExerciseInfo.objects.filter(uploader=nurse)
            while True:
                # 随机选取一个题目
                exercise = random.choice(exercise_list)
                num = exercise.id  # 告诉前端我选到的是那一个题
                if exercise:
                    if len(eval(exercise.answer)) == 1:
                        exercise_type = 0  # 单选题
                    else:
                        exercise_type = 1  # 多选题
                if exercise:
                    break
            return render(request, 'exercise/do-exercise.html', locals())
        elif operate == 'detail':
            pk = request.GET.get('id')
            num = pk  # num会返回前端让前端模板知道你在做哪一道题
            exercise = ExerciseInfo.objects.get(id=pk)
            if exercise:
                if len(eval(exercise.answer)) == 1:
                    exercise_type = 0  # 单选题
                else:
                    exercise_type = 1  # 多选题
            return render(request, 'exercise/do-exercise.html', locals())

        return render(request, 'exercise/do-exercise.html')
        # except Exception as e:
        #     print(e)
        #     # 当题库中没题的时候，随机抽题目就会失败，这时候就跳到题库列表，提示用户当前没有题目
        #     return redirect('exercise:show_exercise')

    def post(self, request):
        """处理提交的做题结果并返回正确与否"""
        your_answer = None
        num = request.POST.get('num')
        exercise = ExerciseInfo.objects.get(id=num)
        correct_answer = exercise.answer
        try:
            result = isinstance(eval(correct_answer), list)
            if result:
                your_answer = request.POST.getlist('answer')
                correct_answer = eval(correct_answer)
        except:
            your_answer = request.POST.get('answer')

        exercise.total_count += 1
        if correct_answer == your_answer:
            exercise.correct_count += 1
            exercise.save()
            return JsonResponse({'code': 1})
        else:
            exercise.save()
            return JsonResponse({'code': 0, 'correct_answer': exercise.answer})


@require_http_methods('GET')
def collect_exercise(request):
    """对题目进行收藏"""
    # 是否收藏标志位
    collect = request.GET.get('collection')
    # 判断当前的做题类型
    operate = request.GET.get('operate')
    # 获得题目的id
    exercise_id = request.GET.get('exercise_id')
    # 如果为1,表示收藏该题
    if collect:
        exercise = ExerciseInfo.objects.get(id=exercise_id)   # 获得题目对象
        exercise.collection = True   # 将题目是否收藏的标志位设为真
        exercise.save()              # 保存
        return redirect(f'/exercise/do_exercise/?id={exercise_id}&operate={operate}')

    return redirect(f'/exercise/do_exercise/?id={exercise_id}&operate={operate}')


class ShowCollection(View):
    """显示已经收藏的题目"""
    def get(self, request):
        # 确定当前登陆者身份
        user_id = request.session.get('user_id')
        nurse = NurseInfo.objects.get(id=user_id)
        # 根据身份来显示他们自己收藏的题目
        if nurse.authority == 1:
            exercise_list = ExerciseInfo.objects.filter(collection=True)
        else:
            exercise_list = ExerciseInfo.objects.filter(collection=True, uploader=nurse)

        paginator = Paginator(exercise_list, 2)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)

        context = {
            'page_obj': page_obj,
        }
        return render(request, 'exercise/collect-exercise.html', context=context)


@require_http_methods('GET')
def cancel_collection(request):
    """取消收藏"""
    pk = request.GET.get('id')

    exercise = ExerciseInfo.objects.get(id=pk)
    exercise.collection = False
    exercise.save()

    return redirect('exercise:show_collection')


@require_http_methods('GET')
def detail_exercise(request):
    """展示题目详情"""
    pk = request.GET.get('id')
    exercise = ExerciseInfo.objects.get(id=pk)

    return render(request, 'exercise/detail-exercise.html', {'exercise': exercise})
